//
//  XMChatBaseSet.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/4.
//

#import "XMChatBaseSet.h"
#import "AlbumPicker.h"
#import <AVFoundation/AVFoundation.h>

@interface XMChatBaseSet () <V2TIMSDKListener, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@end

@implementation XMChatBaseSet

static XMChatBaseSet *chatBaseSet;
static dispatch_once_t onceToken;
+ (instancetype)shareInstance {
    if (!chatBaseSet) {
        dispatch_once(&onceToken, ^{
            chatBaseSet = [[XMChatBaseSet alloc] init];
        });
    }
    return chatBaseSet;
}

- (BOOL)baseSet {
    V2TIMSDKConfig *config = [[V2TIMSDKConfig alloc] init];
    config.logLevel = V2TIM_LOG_INFO;
//    config.logListener = ^(V2TIMLogLevel logLevel, NSString * _Nullable logContent) {
//        NSLog(@"%d-%@", logLevel, logContent);
//    };
    [[V2TIMManager sharedInstance] addIMSDKListener:self];
    return [[V2TIMManager sharedInstance] initSDK:1600078076 config:config];
}

- (void)loginWithUserId:(NSString *)userId
                userSig:(NSString *)userSig
                success:(void(^)(void))successBlock {
    [[V2TIMManager sharedInstance] login:userId userSig:userSig succ:^{
        successBlock ();
    } fail:^(int code, NSString * _Nullable desc) {
        NSLog(@"%d-%@", code, desc);
    }];
}

- (NSString *)getLoginUser {
    return [[V2TIMManager sharedInstance] getLoginUser];
}

- (V2TIMLoginStatus)getLoginStatus {
    return [[V2TIMManager sharedInstance] getLoginStatus];
}

- (void)sendMessageWithSender:(NSString *)sender
                     receiver:(NSString *)receiver
                      content:(NSString *)content
                  messageType:(V2TIMElemType)messageType
                      success:(void (^)(V2TIMMessage *msg))successBlock {
    V2TIMMessage *msg;
    switch (messageType) {
        case V2TIM_ELEM_TYPE_TEXT: {
            msg = [[V2TIMManager sharedInstance] createTextMessage:content];
        }
            break;
        case V2TIM_ELEM_TYPE_IMAGE: {
            msg = [[V2TIMManager sharedInstance] createImageMessage:content];
        }
            break;
        case V2TIM_ELEM_TYPE_SOUND: {
            NSURL *url = [NSURL fileURLWithPath:content];
            AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:url options:nil];
            float duration = (float)CMTimeGetSeconds(audioAsset.duration);
            int formatDuration = duration > 59 ? 60 : duration + 1 ;
            msg = [[V2TIMManager sharedInstance] createSoundMessage:content duration:formatDuration];
            if (!msg) {
                [MBProgressHUD showError:@"消息生成失败"];
                return;
            }
        }
            break;
            
        default:
            break;
    }
    [[V2TIMManager sharedInstance] sendMessage:msg
                                      receiver:receiver
                                       groupID:@""
                                      priority:V2TIM_PRIORITY_NORMAL
                                onlineUserOnly:NO
                               offlinePushInfo:nil
                                      progress:nil
                                          succ:^{
        successBlock (msg);
        NSLog(@"发送成功");
    } fail:^(int code, NSString * _Nullable desc) {
        NSLog(@"%d-%@", code, desc);
    }];
}

- (void)sendCustomMsgWithDic:(NSDictionary *)dic
                      sender:(NSString *)sender
                    receiver:(NSString *)receiver
                     success:(void (^)(V2TIMMessage * _Nonnull))successBlock {
    NSData *orderData = [dic yy_modelToJSONData];
    V2TIMMessage *msg = [[V2TIMManager sharedInstance] createCustomMessage:orderData desc:@"转卖/转赠" extension:@""];
    [[V2TIMManager sharedInstance] sendMessage:msg
                                      receiver:receiver
                                       groupID:@""
                                      priority:V2TIM_PRIORITY_NORMAL
                                onlineUserOnly:NO
                               offlinePushInfo:nil
                                      progress:^(uint32_t progress) {
        
    } succ:^{
        successBlock (msg);
    } fail:^(int code, NSString * _Nullable desc) {
        NSLog(@"%d-%@", code, desc);
    }];
}
//V2TIM_ELEM_TYPE_NONE                      = 0,  ///< 未知消息
//V2TIM_ELEM_TYPE_TEXT                      = 1,  ///< 文本消息
//V2TIM_ELEM_TYPE_CUSTOM                    = 2,  ///< 自定义消息
//V2TIM_ELEM_TYPE_IMAGE                     = 3,  ///< 图片消息
//V2TIM_ELEM_TYPE_SOUND                     = 4,  ///< 语音消息
//V2TIM_ELEM_TYPE_VIDEO                     = 5,  ///< 视频消息
//V2TIM_ELEM_TYPE_FILE                      = 6,  ///< 文件消息
//V2TIM_ELEM_TYPE_LOCATION                  = 7,  ///< 地理位置消息
//V2TIM_ELEM_TYPE_FACE                      = 8,  ///< 表情消息
//V2TIM_ELEM_TYPE_GROUP_TIPS                = 9,  ///< 群 Tips 消息
//V2TIM_ELEM_TYPE_MERGER                    = 10, ///< 合并消息


- (void)getHistoryMessageWithUserId:(NSString *)userId
                            lastMsg:(V2TIMMessage *)lastMsg
                            success:(void (^)(NSArray <V2TIMMessage *> *msg))successBlock {
    [[V2TIMManager sharedInstance] getC2CHistoryMessageList:userId
                                                      count:20
                                                    lastMsg:lastMsg
                                                       succ:^(NSArray<V2TIMMessage *> *msgs) {
        successBlock (msgs);
    } fail:^(int code, NSString * _Nullable desc) {
        
    }];
}

- (void)onConnecting {
    NSLog(@"链接中");
}

- (void)onConnectSuccess {
    NSLog(@"链接成功");
}

- (void)onConnectFailed:(int)code err:(NSString *)err {
    NSLog(@"链接失败%d-%@", code, err);
}

- (void)onKickedOffline {
    NSLog(@"被踢下线");
}

//- (void)selectPhotoWithPresentVC:(XMBaseViewController *)presentVC {
//    if ([AlbumPicker sharedInstance].advancedAlbumPicker) {
//        __weak typeof(self) weakSelf = self;
////        __strong typeof(weakSelf.listener) strongListener = weakSelf.listener;
//        [[AlbumPicker sharedInstance].advancedAlbumPicker pickMediaWithCaller:presentVC
//                                                          originalMediaPicked:^(NSDictionary *param) {
//            if (param) {
//                NSString * type = param[@"type"];
//                if ([type isEqualToString:@"image"]) {
//                    // image do nothing
//                }
////                else if ([type isEqualToString:@"video"]) {
////                    TUIMessageCellData *placeHolderCellData = param[@"placeHolderCellData"];
////                    if ([strongListener respondsToSelector:@selector(sendPlaceHolderUIMessage:)]) {
////                        [strongListener sendPlaceHolderUIMessage:placeHolderCellData];
////                    }
////                    TUIChatMediaTask * task = [[TUIChatMediaTask alloc] init];
////                    task.placeHolderCellData = placeHolderCellData;
////                    task.msgID = placeHolderCellData.msgID;
////                    task.conversationID = weakSelf.conversationID;
////                    if (placeHolderCellData.msgID.length > 0) {
////                        [TUIChatMediaSendingManager.sharedInstance addMediaTask: task forKey:placeHolderCellData.msgID];
////                    }
////                }
////                else {
////                    // do nothing
////                }
//            }
//        } progressCallback:^(NSDictionary *param) {
//            NSLog(@"%@,strongListener:", param);
//        } finishedCallback:^(NSDictionary *param) {
//            if (param) {
//                V2TIMMessage * message = param[@"message"];
//                NSString * type = param[@"type"];
//                if ([type isEqualToString:@"image"]) {
//                    [weakSelf sendMessageWithSender:<#(nonnull NSString *)#> receiver:<#(nonnull NSString *)#> content:<#(nonnull NSString *)#> messageType:<#(V2TIMElemType)#> success:<#^(void)successBlock#>]
//                    if ([strongListener respondsToSelector:@selector(sendMessage:placeHolderCellData:)]) {
//                        [strongListener sendMessage:message placeHolderCellData:nil];
//                    }
//                }
//                else if ([type isEqualToString:@"video"]) {
////                    TUIMessageCellData *placeHolderCellData = param[@"placeHolderCellData"];
////                    if (placeHolderCellData.msgID.length > 0) {
////                        [TUIChatMediaSendingManager.sharedInstance removeMediaTaskForKey:placeHolderCellData.msgID];
////                    }
////                    BOOL canSendByCurrentPage = NO;
////                    for (id<TUIChatMediaDataListener> currentVC in TUIChatMediaSendingManager.sharedInstance.mediaSendingControllers) {
////                        if ([currentVC.currentConversationID isEqualToString:self.conversationID]&&
////                            [currentVC respondsToSelector:@selector(sendMessage:placeHolderCellData:)]) {
////                            if (currentVC.isPageAppears) {
////                                [currentVC sendMessage:message placeHolderCellData:placeHolderCellData];
////                                canSendByCurrentPage = YES;
////                                break;
////                            }
////                        }
////                    }
////                    if (!canSendByCurrentPage) {
////                        if ([strongListener respondsToSelector:@selector(sendMessage:placeHolderCellData:)]) {
////                            [strongListener sendMessage:message placeHolderCellData:placeHolderCellData];
////                        }
////                    }
//                }
//                else {
//                    // do nothing
//                }
//            }
//        }];
//    }
//    else {
//        //defalut AlbumPicker
//        [self _selectPhotoWithPresentVC:presentVC];
//    }
//}

@end
